<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/9/22
 * Time: 14:18
 */

namespace app\alliance\controller;


use app\service\MemberService;
use Redis\Redis;
use think\App;
use think\Controller;
use think\Db;
use Yansongda\Pay\Pay;

class Payment extends Controller
{
    # 商户id
    public $bizId;
    # 微信支付config
    private $wxConfig = [
        'appid' => 'wxbd286076bd81f5d5', // APP APPID
        'mch_id' => '1601889241',
        'key' => 'youpi160188924116018892411601889',
        'notify_url' => 'https://meng.childpi.com/alliance/Payment/payBackWx',//支付回调地址
        'log' => [ // optional
            'file' => '../runtime/payLogs/wechat.log',
            'level' => 'debug', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        // 'mode' => 'dev',
    ];


    # 支付宝支付config
    private $aliConfig = [
        'app_id' => '2021001187619640',
        'notify_url' => 'https://meng.childpi.com/alliance/Payment/payBackAli',
//        'return_url' => 'https://www.8a1.top/alliance/Payment/payBackAli',
        'ali_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAojSPnrmQl1GIIvNrRalo6QsnAYU3Wff3grKnHMoi0xZ6ftKMROB6tUY91AVa85CHld7MkrwZHlvDSjUrtzIfBnevpOSCUKIVgSEf4dO3WMbSlLDU7Pu5xz9gCM7WA6tbtvmszgwmk6piZDenSZcx08e4t1QIeBP5YxGjHM4lk8hPFgdSsP1frY7zVGw+fZxKl+QOcW6MtX89NqQOVe84IgSej4cWhTuSwBdKA5SoHLW2vuauvTwAF+qpETkUO4MzzPqYPTUe05Ap6NDbtVhctFerdbRudjfnYZe7Bgj4ukSz0Jc7eJ/BH/6jTZXYMQW7Ck7DwVShapp4pJoaLag11wIDAQAB',
        'private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ewJTpgBn9EVi/jnYrcfRwKBgQC0JXA38/u4EbRf8ucstmOv/UgzF7X9tAwbVKLJsQZnqtoRCjqQfKI/1zhvXXVlFkRh8V5jyPSST1WDfzyxZZOpnGYci/elJXWnKjFo+KF9mJzSh0UUQoSPEdO/YuRwIgJsMvifQSLT6dPOU2iEQOwADHalNnLTi6Pkoop9S2AV/QKBgDdnxzZrVA2MutXO0iFDUsDBfzcTO4551bIF4pbQdd0Mx2vsiJ/PeMVdmKp3aTkilU0tp77VvqgH/u9BOc5mNSYRMSvefYTNxTd9GJzHWjcsNRFFS1CI4wu4SBFcuhSpc3pWmG8lrcPUS4YIhxJ0ba11PHsppBUHh38BYZOi/ADrAoGBAKL2zLxcjKXtEEdFIvs5o3VLA76RUSDTjR1upcK/7V8nxmM6OxgpR/YBpbvA57tg+2eQh0Vz/JWMHhOCbzbZplehYzw7hDefJ2L5jIOXkLNpAgTRdQaL7Hi2XGihkap3zjarHdaWJtUYaOv1lm1Jv4irpasdSVNlB7r+pfBnuDBQ',
        'log' => [ // optional
            'file' => '../runtime/payLogs/alipay.log',
            'level' => 'debug', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        // 'mode' => 'dev', // optional,设置此参数，将进入沙箱模式
    ];
    # 订单支付信息
    protected $order = [];

    /**
     * Payment constructor.
     * @param array $order
     */
    public function __construct(array $order = array())
    {
        $this->order = $order;
    }
//    public function __construct(App $app = null)
//    {
//        parent::__construct($app);
//        header('Access-Control-Allow-Origin:*');  //支持全域名访问，不安全，部署后需要固定限制为客户端网址
//        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); //支持的http 动作
//        header('Access-Control-Allow-Headers:Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Authorization , Access-Control-Request-Headers,token');  //响应头 请按照自己需求添加。
//        if (strtoupper($_SERVER['REQUEST_METHOD']) == 'OPTIONS') {
//            exit;
//        }
//    }

    /**
     * @return array
     * @content 微信支付
     */
    function wxPay()
    {
        $res = Pay::wechat($this->wxConfig)->app($this->order);
        $json = $res->getContent();
        return array('status' => true, 'data' => $json);
    }

    /**
     * @return array
     * @content 支付宝支付
     */
    function aliPay()
    {
        $res = Pay::alipay($this->aliConfig)->app($this->order);
        $json = $res->getContent();
        return array('status' => true, 'data' => $json);
    }

    /**
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 阿里支付回调
     */
    function payBackAli()
    {
        $testxml = $_POST;
        $jsonxml = json_encode($testxml);
        Db::table('pay_back')->insert(array('info' => $jsonxml, 'type' => 'ali'));
        $returnInfo = json_decode($jsonxml, true);
        if ($returnInfo['trade_status'] == 'TRADE_SUCCESS') {
            # 支付成功,
            $rechargeInfo = Db::table('log_recharge')->where(array('out_trade_no' => $returnInfo['out_trade_no']))->find();
            if (!empty($rechargeInfo)) {
                $gold_num = $rechargeInfo['recharge_gold'] + $rechargeInfo['give_gold'];
                # 加金币
                Db::table('member_property')
                    ->where(array('member_code' => $rechargeInfo['member_code']))
                    ->setInc('gold', $gold_num);
                # 金币记录
                MemberService::addLog_gold($rechargeInfo['member_code'], $gold_num, 20, '', 0, $returnInfo['out_trade_no']);
                # 充值记录
                Db::table('log_recharge')->where(array('id' => $rechargeInfo['id']))->update(array('status' => 2, 'notify_time' => $returnInfo['notify_time']));
                # 更新用户redis
                $redis = new Redis();
                $memberInfo = $redis->hGetJson('memberInfo', $rechargeInfo['member_code']);
                $memberInfo['gold'] = priceFormat($memberInfo['gold'] + $gold_num);
                $redis->hSetJson('memberInfo', $rechargeInfo['member_code'], $memberInfo);
            }
        }
        echo(Pay::alipay($this->aliConfig)->success()->getContent());
    }

    function payBackWx()
    {
        $testxml = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        Db::table('pay_back')->insert(array('info' => $jsonxml, 'type' => 'wx'));
        echo(Pay::wechat($this->wxConfig)->success()->getContent());
    }

}